<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/11/17
 * Time: 下午2:06
 */

class ModUserRoleMap extends Model {

    protected $table = 'tblUserRoleMap';

    // 表名
    public function tableName(){
        return $this->table;
    }

    public static function model($className=__CLASS__){
        return parent::model($className);
    }

    public function getDbConnection(){
        return Yii::app()->dbAuth;
    }
    
    /**
     * 获取某个角色下的所有用户
     */
    public function getRoleUserList($RoleID){
    	$sql = "SELECT * FROM {$this->table} WHERE RoleID=:RoleID";
        $args = array(':RoleID' => $RoleID);
        $tmp = $this->getDbConnection()->getAll($sql, $args);
        return $tmp;
    }

    /**
     * 获得一个用户的游戏信息
     * @param $userId
     * @return array
     */
    public function getUserGame($userId, $change=false){
        $sql = 'SELECT PlatformID,GameID FROM tblUserRoleMap WHERE UserID=:UserID GROUP BY PlatformID,GameID';
        $args = array(':UserID' => $userId);

        if($change){
            $modPlatformGameMap = new ModPlatformGameMap();
            $gamePlatformMap = $platformGameMap = array();
            foreach($modPlatformGameMap->select() as $v){
                $gamePlatformMap[$v['GameID']][] = $v['PlatformID'];

                $platformGameMap[$v['PlatformID']][] = $v['GameID'];
            }
        }

        $tmp = $this->getDbConnection()->getAll($sql, $args);
        $result = array();
        if(!empty($tmp) && is_array($tmp)){
            foreach($tmp as $v){
                if($change && $v['PlatformID'] == -1 && !empty($gamePlatformMap[$v['GameID']])){
                    foreach($gamePlatformMap[$v['GameID']] as $pv){
                        $key = "{$pv}-{$v['GameID']}";
                        $result[$key] = $key;
                    }
                }else if($change && $v['GameID'] == -1 && !empty($platformGameMap[$v['PlatformID']])){
                    foreach($platformGameMap[$v['PlatformID']] as $gv){
                        $key = "{$v['PlatformID']}-{$gv}";
                        $result[$key] = $key;
                    }
                }else{
                    $key = "{$v['PlatformID']}-{$v['GameID']}";
                    $result[$key] = $key;
                }
            }
        }

        return $result;
    }
} 